﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	CleanupJob.cs
//  Developer:	Solomatov Igor
//  Created:	16.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.SharePoint;

namespace Smart.Common.Jobs
{
	/// <summary>
	/// Cleanup templib job
	/// </summary>
	public class CleanupJob : SPJob
	{
		/// <summary>
		/// Cleanup templib job
		/// </summary>
		public CleanupJob()
		{
		}

		/// <summary>
		/// Cleanup templib job
		/// </summary>
		public CleanupJob(string jobName, SPSite site, SPWeb web)
			: base(jobName, jobName, site, web)
		{
		}

		protected override void ExecuteInternal()
		{
			try
			{
				var web = SPH.GetRootWeb();

				using (new UnsafeUpdate(web))
				{
					var list = web.GetListByUrl("Cleanup");

					if (list == null)
						throw new FileNotFoundException("Cleanup");

					UpdateProgress(5);

					var removeItems =
						list.Query().Where.Lt(SPBuiltInFieldId.Modified.ToString(), DateTime.Now.AddDays(-1)).Executor.GetItems();

					var items = removeItems.Cast<SPListItem>().Reverse().ToList();

					UpdateProgress(50);

					for (int i = 0, iMax = items.Count; i < iMax; i++)
					{
						var item = items[i];

						// Update progress every 8 items
						if ((i & 0x7) == 0)
							UpdateProgress(50 + i * 50 / items.Count);

						// Remove completely (avoiding recycle bin)
						item.Delete();
					}

					UpdateProgress(100);
				}
			}
			catch (Exception ex)
			{
				H.LX("CleanupJob.ExecuteInternal", ex);
			}
		}
	}
}